package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.arlen.photo.photopickup.presenter.HeadPresenter;
import com.arlen.photo.photopickup.util.DensityUtils;
import com.baidu.mapapi.common.SysOSUtil;
import com.google.gson.JsonObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Hashtable;


/**
 * 我的二维码
 *
 * @author yejianjun
 */
public class MyQRCodeActivity extends BaseActivity {

    private ImageView userHead;
    private TextView userName;
    private TextView userLabel;
    private ImageView sexIV;
    private ImageView addV;
    private ImageView qrCodeImage;
    private Dialog dialog;
    private LinearLayout myLinearLayout;
    private ImageButton rightImageBtn;
    //    private CommentLongClickHelper commentLongClickHelper;
    private final int TYPE_SAVE = 1;
    private final int TYPE_SHARE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.my_qr_code, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.my_qr_code));
//        commentLongClickHelper = CommentLongClickHelper.getInstance();
        initView();
        initData();

    }

    private void initView() {
        myLinearLayout = findViewById(R.id.qr_code_layout);
        userHead = findViewById(R.id.user_head);
        userName = findViewById(R.id.user_name);
        userLabel = findViewById(R.id.user_label);
        sexIV = findViewById(R.id.user_sex);
        addV = findViewById(R.id.add_v_iv);
        qrCodeImage = findViewById(R.id.qr_code_imageview);
        rightImageBtn = findViewById(R.id.right_imagebutton);
        rightImageBtn.setVisibility(View.VISIBLE);
        rightImageBtn.setImageResource(R.drawable.sandian);
        rightImageBtn.setOnClickListener(this);
        rightImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(MyQRCodeActivity.this, myLinearLayout);
            }
        });

    }

    private void initData() {
        userName.setText(GlobalContext.getNiceName() == null ? "" : GlobalContext.getNiceName());
        userLabel.setText(GlobalContext.getLabel() == null ? "" : GlobalContext.getLabel());
        PictureDownloadUtils.displayHeadImage(this, userHead, GlobalContext.getHeadPic());
        Utils.showSex(this, GlobalContext.getSex(), sexIV);
        if (GlobalContext.getIndustryAuthority()) {
            addV.setVisibility(View.VISIBLE);
        } else {
            addV.setVisibility(View.GONE);
        }
        // 二维码内容格式：{"accountId":"121212"}
        JsonObject ob = new JsonObject();
        ob.addProperty("accountId", String.valueOf(GlobalContext.getAccountId()));
        String sourse = ob.toString();
        if (!sourse.equals("")) {
            try {
                Bitmap bitmap = Create2DCode(sourse);
                qrCodeImage.setImageBitmap(createBitmap(bitmap, zoomBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher), 100, 100)));
            } catch (WriterException e) {
                e.printStackTrace();
            }
        }

    }

    public Bitmap Create2DCode(String str) throws WriterException {
//        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.CHARACTER_SET, "GBK");
        // hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        int screen_width = DensityUtils.getWindowWidth(this);
        screen_width = screen_width - Utils.dip2px(this, 60);
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, screen_width, screen_width, hints);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int[] pixels = new int[width * height];
        for (int i = 0; i < pixels.length; i++) {
            pixels[i] = 0xffffffff;
        }
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap,具体参考api
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    /***
     * 合并图片
     *
     * @param src
     * @param watermark
     * @return
     */
    private Bitmap createBitmap(Bitmap src, Bitmap watermark) {
        String tag = "createBitmap";
//        Log.d(tag, "create a new bitmap");
        if (src == null) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        int ww = watermark.getWidth();
        int wh = watermark.getHeight();
        // create the new blank bitmap
        Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
        Canvas cv = new Canvas(newb);
        // draw src into
        cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
        // 在src的中间画watermark
        cv.drawBitmap(watermark, w / 2 - ww / 2, h / 2 - wh / 2, null);// 设置ic_launcher的位置
        // save all clip
        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
        // store
        cv.restore();// 存储
        return newb;
    }

    /***
     * 缩放图片
     *
     * @param src
     * @param destWidth
     * @param destHeigth
     * @return
     */
    private Bitmap zoomBitmap(Bitmap src, int destWidth, int destHeigth) {
        String tag = "lessenBitmap";
        if (src == null) {
            return null;
        }
        int w = src.getWidth();// 源文件的大小
        int h = src.getHeight();
        // calculate the scale - in this case = 0.4f
        float scaleWidth = ((float) destWidth) / w;// 宽度缩小比例
        float scaleHeight = ((float) destHeigth) / h;// 高度缩小比例
        Matrix m = new Matrix();
        m.postScale(scaleWidth, scaleHeight);// 设置矩阵比例
        Bitmap resizedBitmap = Bitmap.createBitmap(src, 0, 0, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行
        return resizedBitmap;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

            default:
                break;
        }

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 显示保存图片弹出框
     */
    private void showDialog(final Context context, final View picView) {
        final Dialog dialog = new Dialog(context, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
            win.setWindowAnimations(R.style.buttom_animation);
        } catch (Exception e) {
            e.printStackTrace();
        }


        View view = LayoutInflater.from(context).inflate(R.layout.custom_save_pic_dialog, null);
        Button shareBtn = view.findViewById(R.id.share_qrcode);
        Button saveBtn = view.findViewById(R.id.save_pic);
        Button cancelBtn = view.findViewById(R.id.cancel);

        dialog.setCanceledOnTouchOutside(true);
        // 分享
        shareBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                saveOrShareBitmap(context, picView, TYPE_SHARE);

            }
        });
        // 保存二维码图片
        saveBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                saveOrShareBitmap(context, picView, TYPE_SAVE);
            }
        });
        // 取消
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();

    }

    private Bitmap createViewBitmap(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

    private void saveOrShareBitmap(final Context context, final View picView, final int type) {
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {

                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Bitmap bmp = createViewBitmap(picView);
                    File appDir = new File(Environment.getExternalStorageDirectory(), "DnImage");
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    String fileName = System.currentTimeMillis() + ".jpg";
                    File file = new File(appDir, fileName);
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
//                        if (type == ScannerType.RECEIVER) {
//                        } else if (type == ScannerType.MEDIA) {
//                            ScannerByMedia(context, file.getAbsolutePath());
//                        }
                        ScannerByMedia(context, file.getAbsolutePath());
                        if (!bmp.isRecycled()) {
                            // bitmap.recycle(); 当存储大图片时，为避免出现OOM ，及时回收Bitmap
                            System.gc(); // 通知系统回收
                        }
//                        Notification.showToastMsg(context,"图片保存为" + file.getAbsolutePath());
                    }

                    // 其次把文件插入到系统图库
                    /*try {
//                        MediaStore.Images.Media.insertImage(getContentResolver(), "image path", "title", "description");
                        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                file.getAbsolutePath(), fileName, null);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }*/
                    // 最后通知图库更新

                    return file.getAbsolutePath();
                } else {
                    Notification.showToastMsg(context, "未检测到存储卡，无法保存");
                    return null;
                }

            }

            @Override
            protected void onPostExecute(Object o) {
                if (null != o) {
                    if (type == TYPE_SAVE) {
                        Notification.showToastMsg(context, "图片已保存到:" + o);
                    } else if (type == TYPE_SHARE) {
                        String prefix_url = null;
                        GlobalUserData userData = new GlobalUserData();
                        if (userData.getEnvironemt().equals("qa")) {
                            prefix_url = ShareSDKManager.TEST_SERVICE_URL;
                        } else {
                            prefix_url = ShareSDKManager.SERVICE_URL;
                        }
                        String end = "&&t=" + userData.getEnvironemt();
                        // 调用分享
                        ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                        shareSDKManager.sharePic(context, o.toString(), prefix_url, end);
                    }
                }
            }
        }.execute();

    }

    @Override
    protected void onDestroy() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        super.onDestroy();
    }


    /**
     * Receiver扫描更新图库图片
     * file:// 7。0系统权限异常
     **/
    /*private static void ScannerByReceiver(Context context, String path) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + path)));
        Log.v("TAG", "receiver scanner completed");
    }*/

    /**
     * MediaScanner 扫描更新图库图片
     **/
    private static void ScannerByMedia(Context context, String path) {
        MediaScannerConnection.scanFile(context, new String[]{path}, null, null);
        Log.v("TAG", "media scanner completed");
    }


}
